/* eslint-disable */
import store from "@/store";
import ChinaTowerMapOL from "@/utils/ChinaTowerMapOL";
import postMsgUtil from "@/utils/PostMsgUtil";
import {
  copyToClipboard,
  exitFullscreen,
  fullScreen,
  getToken,
  getWindowInfo,
  getWindowRatio,
  getWindowScaling,
} from "@/utils/common";
import EventBus from "@/utils/event-bus";
import * as iframeUtil from "@/utils/iframeUtil"; //NOSONAR
import postMsgSDK from "@/utils/postMessageSDK"; // 业务功能需要引入自身执行 勿删
import CryptoJS from "crypto-js";
import Vue from "vue";


// maps 队列
const queueMaps = new Map();
const mapInstanceQueueMaps = new Map();
const encryptKey = CryptoJS.enc.Utf8.parse(CryptoJS.enc.Base64.parse(
  process.env.VUE_APP_KEY
).toString(CryptoJS.enc.Utf8));
function encrypt(content) {
  return CryptoJS.AES.encrypt(content, encryptKey, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  }).toString();
}

/**
 * 格式化 className
 * @param {*} className
 * @returns string
 */
function formatClassName(className, index = 0) {
  if (className.split("-").length < 2) {
    return `${className}-${index}`;
  } else {
    const classNames = className.split("-");
    if (/^\d+$/.test(classNames[1])) {
      return className;
    } else {
      return `${classNames[0]}-${index}`;
    }
  }
}

/**
 * 获取iframe信息
 *
 * @param {Array} iframeIds iframe的ID数组
 * @returns {Object} iframeInfo 包含iframe信息的对象
 */
function getIframeInfo(iframeIds){
  const iframeInfo = {};
  if (iframeIds) {
    iframeIds.forEach((item) => {
      const element = document.getElementById(item);
      if (element) {
        iframeInfo[item] = {
          offsetTop: element.parentNode.offsetTop,
          offsetLeft:
            element.parentNode.offsetLeft,
          offsetWidth:
            element.parentNode.offsetWidth,
          offsetHeight:
            element.parentNode.offsetHeight,
        };
      }
    });
  }
  return iframeInfo;
}

/**
 * 获取浏览器窗口信息
 *
 * @param params 参数对象
 * @param params.iframeIds 需要获取信息的iframe的id数组
 * @returns 返回包含浏览器窗口信息的对象
 */
function getWindowInformation(params){
  const iframeContainers = document.getElementsByClassName("iframeContainer");
  let iframeOffsetWidth;
  let iframeOffsetHeight;
  if (iframeContainers.length) {
    const currentIframe =
      iframeContainers.length === 1
        ? [...iframeContainers][0]
        : [...iframeContainers].find(
            (item) =>
              item.style.display === "block" ||
              (item.style.display === "" &&
                window.getComputedStyle(item, null)["display"] ===
                  "block")
          );
    iframeOffsetWidth = currentIframe?.offsetWidth;
    iframeOffsetHeight = currentIframe?.offsetHeight;
  }
  const innerWidth =
    window.innerWidth ||
    document.documentElement.clientWidth ||
    document.body.clientWidth; // 页可见区域宽
  const innerHeight =
    window.innerHeight ||
    document.documentElement.clientHeight ||
    document.body.clientHeight; // 网页可见区域高
  const offsetWidth = iframeOffsetWidth || document.body.offsetWidth; // 网页可见区域宽
  const offsetHeight = iframeOffsetHeight || document.body.offsetHeight; // 网页可见区域高
  const scrollWidth = document.body.scrollWidth; // 网页正文全文宽
  const scrollHeight = document.body.scrollHeight; // 网页正文全文高
  const scrollTop =
    document.body.scrollTop || document.documentElement.scrollTop; // 网页被卷去的高
  const scrollLeft = document.body.scrollLeft; // 网页被卷去的左
  const screenTop = window.screenTop; // 网页正文部分上
  const screenLeft = window.screenLeft; // 网页正文部分左
  const height = iframeOffsetHeight || window.screen.height; // 屏幕分辨率的高
  const width = iframeOffsetWidth || window.screen.width; // 屏幕分辨率的宽
  const availHeight = window.screen.availHeight; // 屏幕可用工作区高度
  const availWidth = window.screen.availWidth; // 屏幕可用工作区宽度

  const _data = {
    innerWidth,
    innerHeight,
    offsetWidth,
    offsetHeight,
    scrollWidth,
    scrollHeight,
    scrollTop,
    scrollLeft,
    screenTop,
    screenLeft,
    width,
    height,
    availHeight,
    availWidth,
  };

  const iframeInfo = getIframeInfo(params?.iframeIds);
  if (Object.keys(iframeInfo).length) {
    _data.iframeInfo = iframeInfo;
  }

  return _data
}

/**
 * 处理默认操作
 *
 * @param {string} targetIframe - 目标iframe的标识，可以是"default"或iframe的id
 * @param {HTMLIFrameElement} iframe - iframe元素
 * @param {any} otherData - 其他数据
 * @param {Object} $postMsgUtil - $postMsgUtil工具对象
 * @throws {Error} - 当找不到iframe时抛出错误
 */
function handleDefaultOperation(targetIframe, iframe, otherData, $postMsgUtil) {
  const iframeDom = targetIframe === "default" ? iframe : document.getElementById(targetIframe);

  if (iframeDom) {
      $postMsgUtil.trigger(
          iframeDom,
          "iframeMiddlewareCallBack",
          { data: otherData },
          (data) => {
              console.log(`iframeMiddleware to iframe [${iframeDom}] `, data);
          }
      );
  } else {
      throw new Error("iframe not found");
  }
}

/**
 * iframe操作函数
 *
 * @param {Object} $postMsgUtil 消息传递工具
 * @param {Object} params 参数对象
 * @param {HTMLIFrameElement} iframe iframe元素
 * @param {string} enKeys 密钥
 * @param {string} url 请求地址
 * @param {Object} _vue Vue实例
 */
function iframeOperations($postMsgUtil, params, iframe, enKeys, url, _vue){
  const {
    targetIframe = "default",
    iframeOperationId = "",
    needBack = false,
    ...otherData
  } = params;
  otherData.originIframeId = iframe.getAttribute("id");
  if (iframeOperationId) {
    if (
      [
        "moveUrl",
        "moveIframeUrl",
        "addUrl",
        "delUrl",
        "handleAudioRecorder",
      ].includes(iframeOperationId)
    ) {
      // 执行iframe的相关操作
      try {
        iframeUtil[iframeOperationId](otherData, _vue)
          .then((res) => {
            needBack && $postMsgUtil.trigger(iframe, enKeys + url, { data: res });
          })
          .catch((error) => {
            $postMsgUtil.trigger(iframe, enKeys + url, {
              data: {
                code: -1,
                msg: error,
              },
            });
          });
      } catch (error) {
        throw new Error(
          `iframeOperationId[${iframeOperationId}] not support.${error}`
        );
      }
    } else {
      // 执行iframe的相关操作
      try {
        const result = iframeUtil[iframeOperationId](otherData, _vue);
        needBack && $postMsgUtil.trigger(iframe, enKeys + url, { data: result });
      } catch (error) {
        throw new Error(
          `iframeOperationId[${iframeOperationId}] not support.${error}`
        );
      }
    }
  } else {
    handleDefaultOperation(targetIframe, iframe, otherData, $postMsgUtil);
  }
}

/**
 * 请求工具函数
 *
 * @param {Object} $postMsgUtil 消息传递工具
 * @param url 请求地址
 * @param params 请求参数
 * @param headers 请求头
 * @param method 请求方法
 * @param responseType 响应类型
 * @param enKeys 加密键值
 * @param iframe iframe元素
 */
function requestUtils($postMsgUtil, url, params, headers, method, responseType, enKeys, iframe){
  Vue.prototype.$sdk
    .request(url, params, headers, method, responseType)
    .then((res) => {
      if (responseType === "blob") {
        if (params.fileType) {
          const blob = new Blob([res], { type: params.fileType });
          const fileName = params.fileName || "download";
          const alink = document.createElement("a");
          alink.download = fileName;
          alink.style.display = "none";
          alink.href = URL.createObjectURL(blob);
          document.body.appendChild(alink);
          alink.click();
          URL.revokeObjectURL(alink.href);
          document.body.removeChild(alink);

          $postMsgUtil.trigger(iframe, enKeys + url, {
            code: 200,
            msg: "下载成功",
            data: "",
          });
        } else {
          const reader = new FileReader();
          reader.readAsText(res);
          reader.onload = function () {
            let resp = JSON.parse(reader.result);

            $postMsgUtil.trigger(iframe, enKeys + url, {
              code: 201,
              msg: resp.msg,
              data: "",
            });
          };
        }
      } else {
        $postMsgUtil.trigger(
          iframe,
          enKeys + url,
          { ...res }
        );
      }
    })
    .catch((e) => {
      // 将错误信息抛回去给iframe
      let { message } = e;
      let code = "";
      if (message === "Network Error") {
        message = "系统接口请求异常";
      } else if (message.includes("timeout")) {
        message = "系统接口请求超时";
      } else if (message.includes("Request failed with status code")) {
        code = message.substr(message.length - 3);
      } else {
        console.log("sonar");
      }
      $postMsgUtil.trigger(
        iframe,
        enKeys + url,
        {
          code,
          message,
        }
      );
    });
}

/**
 * 生成完整的URL
 *
 * @param {string} url - 原始URL
 * @param {string} searchParams - 查询参数字符串
 * @param {string} metaTitle - meta标题
 * @returns {string} 完整的URL
 */
function generateFullUrl(url, searchParams, metaTitle) {
  let fullUrl = url;

  if (url.indexOf("?") > -1) {
    fullUrl = `${url}${searchParams ? `&${searchParams}` : ""}${
      metaTitle ? `&metaTitle=${metaTitle}` : ""
    }&noCache=${new Date().getTime()}`;
  } else {
    fullUrl = `${url}?noCache=${new Date().getTime()}`;
    fullUrl = `${fullUrl}${searchParams ? `&${searchParams}` : ""}${
      metaTitle ? `&metaTitle=${metaTitle}` : ""
    }`;
  }

  return fullUrl;
}


/**
 * 处理重定向到指定URL
 *
 * @param {string} url - 目标URL
 * @param {string} route - 路由名称
 * @param {object} params - 参数对象
 * @param {Vue} _vue - Vue实例
 * @param {boolean} isOpener - 是否使用新窗口打开链接
 */
function handleRedirectTo(url, route, params, _vue, isOpener = false){
  let searchParams = "";
  let _metaTitle = "";
  if (params) {
    const { metaTitle, ..._params } = params;
    searchParams = new URLSearchParams(_params).toString();
    _metaTitle = metaTitle;
  }

  url = generateFullUrl(url, searchParams, _metaTitle);

  if (isOpener) {
    window.open(url);
  } else {
    // 对url进行编码
    url = encodeURIComponent(url);
    const selectedTag = _vue.$store.getters.visitedViews.find(
      (item) => item.fullPath === `/redirectPage?url={url}`
    );
    if (selectedTag) {
      selectedTag.title = _metaTitle || selectedTag.title;
      _vue.$store.dispatch("tagsView/updateVisitedView", selectedTag);
    }
    _vue.$router.push({
      path: "/redirectPage",
      query: {
        url,
        metaTitle: _metaTitle || "编辑页面",
      },
    });
  }
}
/**
 * 跳转到其他页面
 *
 * @param {Object} param0 包含url、params、isOpener对象的参数对象
 * @param {string} param0.url 跳转页面的url地址
 * @param {Object} param0.params 跳转页面的参数对象，默认为空对象
 * @param {boolean} param0.isOpener 是否通过新窗口打开页面，默认为false
 * @returns {Error|undefined} 如果url为空，返回错误对象
 */
function redirectToOtherPage({ url, params = {}, isOpener = false })  {
    if (!url) {
      return new Error('url is required')
    }
    if (isOpener) {
      const searchParams = new URLSearchParams(params).toString()
      if (url.indexOf('?') > -1) {
        url = `${url}${searchParams ? `&${searchParams}` : ''}&noCache=${new Date().getTime()}`
      } else {
        url = `${url}?noCache=${new Date().getTime()}`
        url = `${url}${searchParams ? `&${searchParams}` : ''}`
      }
      window.open(url, "_blank", "noopener=yes,noreferrer=yes");
    } else {
      EventBus.$emit("openCommonBanner", { url, params, isOpener });
    }
  }
/**
 * 处理返回原点
 *
 * @param data 数据
 * @param _vue vue实例
 */
function handleBackToOrigin(data, isClose, _vue){
  const { originKey, ..._data } = data;

  if (isClose) {
    // 关闭当前窗体
    const selectedTag = _vue.$store.getters.visitedViews.find(
      (item) => item.path === "/redirectPage" && item.fullPath === _vue.$route.fullPath
    );
    _vue.$store.dispatch("tagsView/delView", selectedTag);
  }

  // 切换到某个tag
  const originRoutePage =
    _vue.$store.getters.queuePages[originKey.replaceAll(" ", "+")];

  let toTag = null;
  if (originRoutePage) {
    toTag = _vue.$store.getters.visitedViews.find(
      (item) => item.fullPath === originRoutePage["fullPath"]
    );
  } else {
    toTag =
      _vue.$store.getters.visitedViews[
        _vue.$store.getters.visitedViews.length - 1
      ];
  }
  _vue.$router.push(toTag);
}

/**
 * 处理监听飞马组件消息的函数
 *
 * @param {object} data - 消息数据
 * @param {object} _vue - Vue实例
 */
function handleListenChangeMenuSrc(data, _vue) {
  console.log("listenFlyManaMessage", data);
  const _iframe = document.getElementById(data.domId);
  let src_ = data.targetUrl;
  let searchStr = "";
  if (data.param) {
    // 拼接参数
    Object.keys(data.param).forEach((_key) => {
      searchStr += `&${_key}=${data.param[_key]}`;
    });
  }
  _iframe.src = src_ + searchStr;
  _vue.$nextTick(() => {
    postMsgSDK(_iframe, _vue); //业务功能需要引入自身执行 勿删
  });
}

/**
 * 处理地图初始化
 *
 * @param index 视图索引
 * @param opts 地图配置项
 * @param key 地图标识键值
 * @param $postMsgUtil 消息工具类
 * @param iframe 目标iframe
 * @param data 地图初始化数据
 */
function handleMapInit(index, opts, key, $postMsgUtil, iframe, data) {
  // 先销毁上一次同一个视图的地图
  let existMapKey = "";
  mapInstanceQueueMaps.forEach((item, __key) => {
    if (__key.startsWith(`mapOL-${index}-`)) {
      existMapKey = __key;
      item.destroy();
    }
  });
  if (existMapKey) {
    mapInstanceQueueMaps.delete(existMapKey);
  }

  let mapInstance = queueMaps.get(key);
  if (!mapInstance) {
    mapInstance = new ChinaTowerMapOL({ ...opts, index });
    queueMaps.set(key, mapInstance);
  }

  const enKeys = encrypt(JSON.stringify(data));
  mapInstance.initMap().then((res) => {
    mapInstanceQueueMaps.set(res.id, res.map);
    $postMsgUtil.trigger(iframe, `${enKeys}init`, {
      data: { id: res.id },
    });
  });
}

/**
 * 处理地图实例化
 *
 * @param {string} iSource - 地图来源
 * @param {string} className - 类名
 * @param {number} index - 索引
 * @param {object} opts - 选项
 * @param {object} classOptions - 类选项
 * @param {string} key - 键
 * @param {object} $postMsgUtil - $postMsgUtil对象
 * @param {string} iframe - iframe
 * @param {object} data - 数据
 */
function handleMapInstantiation(iSource, className, index, opts, classOptions, key, $postMsgUtil, iframe, data) {
  const enKeys = encrypt(JSON.stringify(data));
  let mapInstance = queueMaps.get(key);
  if (!mapInstance) {
    mapInstance = new ChinaTowerMapOL({ ...opts, index });
    queueMaps.set(key, mapInstance);
  }
  mapInstance.instantiation(iSource, className, index, opts, classOptions)
    .then((res) => {
      $postMsgUtil.trigger(iframe, `${enKeys}${className}instantiation`, { data: res });
    })
    .catch((error) => {
      console.error(error);
    });
}

/**
 * 处理地图OL中间件
 *
 * @param data 数据对象
 * @param $postMsgUtil 工具对象，用于向父窗口发送消息
 * @param iframe 当前iframe元素
 * @param _vue Vue实例
 */
function handleMapOLMiddleWare(data,$postMsgUtil, iframe, _vue){
  // iSource 实例来源，native OL原生、proxy 代理OL 即 CtMapOL、extend 扩展
  let {
    options: {
      iSource = "proxy",
      className = "Map-0",
      method = "undefined",
      o_id = "",
      o_attr = "",
      event = "",
      index = 0,
      ...opts
    },
    classOptions = {},
  } = data;
  if (method === "undefined") {
    throw new Error("Method Must Required");
  }
  className = formatClassName(className, index);
  let mapInstance = null;
  let enKeys = "";
  const key = `chinaTowerMapOLInstance-${index}`;
  let mapKey = {
    key: "",
    index: 0,
  };
  switch (method) {
    case "init":
      // 初始化地图
      handleMapInit(index, opts, key, $postMsgUtil, iframe, data);
      break;
    case "instantiation":
      // 实例化类
      handleMapInstantiation(iSource, className, index, opts, classOptions, key, $postMsgUtil, iframe, data);
      break;
    case "eventListener":
      // 事件监听
      enKeys = encrypt(JSON.stringify(data));
      mapInstance = queueMaps.get(key);
      const cb = function (res) {
        Object.assign(res, { eventId: `${enKeys}${o_id}${method}` });
        $postMsgUtil.trigger(iframe, `${enKeys}${o_id}${method}`, {
          data: res,
        });
      };
      mapInstance
        .handleEvent(event, o_id, opts, classOptions, cb)
        .then((res) => {
          Object.assign(res, { eventId: `${enKeys}${o_id}${method}` });
          $postMsgUtil.trigger(iframe, `${enKeys}${o_id}${method}`, {
            data: res,
          });
        });
      break;
    case "eventsHandler":
      // 事件处理
      enKeys = encrypt(JSON.stringify(data));
      const {
        options: { id },
      } = data;
      if (id) {
        if (document.getElementById(id)) {
          // eslint-disable-next-line no-async-promise-executor
          return new Promise((resolve, reject) => {
            document.getElementById(id).setAttribute("data-callback", true);
            document.getElementById(id).click();
            resolve();
          });
        }
      } else {
        throw new Error("id must required");
      }
      break;
    case "element":
      enKeys = encrypt(JSON.stringify(data));
      mapInstance = queueMaps.get(key);
      mapInstance.handleElement(opts, iframe, $postMsgUtil).then((res) => {
        $postMsgUtil.trigger(iframe, `${enKeys}${method}`, {
          ...res,
        });
      });
      break;
    default:
      // 其他api
      if (className !== "Map") {
        opts.className = className;
      }
      enKeys = encrypt(JSON.stringify(data));
      mapInstance = queueMaps.get(key);
      mapInstance
        .handleApi(
          method,
          index,
          o_id,
          opts,
          classOptions,
          iframe,
          $postMsgUtil
        )
        .then((res) => {
          $postMsgUtil.trigger(iframe, `${enKeys}${o_id}${method}`, {
            data: res,
          });
        });
      break;
  }
}


/**
 * iframe 要监听的iframe对象
 * data-mode：domain/null为域名，full为全路径
 */
/* eslint-disable no-case-declarations */
/* eslint-disable no-unused-vars */
export default (iframe, _vue) => {
  // 使用全局的队列
  const $postMsgUtil =
    iframe.getAttribute("data-mode") === "full"
      ? Vue.prototype.postMsgUtil
      : postMsgUtil;
  $postMsgUtil.listen(
    "middleLink",
    function (data) {
      const {
        url,
        params = {},
        headers = {},
        method = "get",
        responseType = "json",
      } = data;
      const _keys = { url, params, headers, method, responseType };
      const enKeys = encrypt(JSON.stringify(_keys));
      switch (url) {
        // 校验是否跨域
        case "checkCross":
          const parentUrl = `${window.location.protocol}//${window.location.host}`;

          const urls = iframe.src.split("/");
          const iframeSrc = `${urls[0]}/${urls[1]}/${urls[2]}`;

          $postMsgUtil.trigger(
            iframe,
            "checkCrossResult",
            {
              data: parentUrl === iframeSrc ? 200 : 201,
            },
            (callBackData) => {
              console.log(
                `[${iframe}] parent postmessage trigger checkCross callback`,
                callBackData
              );
            }
          );

          break;
        // 复制文字
        case "copyText":
          copyToClipboard(params);
          break;
        // 获取window info
        case "getUser":
          $postMsgUtil.trigger(iframe, enKeys + url, {
            userInfo: store.getters.userInfo,
            token: getToken(),
            permissions: store.getters.permissions,
            towerAccount: JSON.parse(sessionStorage.getItem("towerAccount")),
          });
          break;
        // 获取window info
        case "getWindowInfo":
          const windowInfoData = getWindowInformation(params);
          $postMsgUtil.trigger(iframe, enKeys + url, {
            data: windowInfoData,
          });
          break;
        // 获取window Ratio
        case "getWindowRatio":
          const ratioData = getWindowRatio();
          const screen = getWindowInfo();
          const windowInfo = Object.assign({}, ratioData, { screen });

          $postMsgUtil.trigger(iframe, enKeys + url, {
            data: windowInfo,
          });
          break;
        case "getCurrentNeedAlertMsg":
          // 获取当前的消息通知信息并清除掉信息
          // 获取store中currentNeedAlertMsg的值
          const msgInfo = _vue.$store.getters.currentNeedAlertMsg;
          _vue.$store.dispatch("removeCurrentNeedAlertMsg");
          $postMsgUtil.trigger(iframe, enKeys + url, {
            data: msgInfo,
          });
          break;
        // 获取缩放比例（包括浏览器的缩放及窗口大小的缩放）
        case "getWindowScaling":
          const scaling = getWindowScaling();
          const screen1 = getWindowInfo();

          $postMsgUtil.trigger(iframe, enKeys + url, {
            data: {
              scaling,
              screen: screen1,
            },
          });
          break;
        // 全屏
        case "fullScreen":
          fullScreen();
          $postMsgUtil.trigger(iframe, enKeys + url, {
            data: {
              message: "fullScreen success",
            },
          });
          break;
        // 退出全屏
        case "exitFullscreen":
          exitFullscreen();
          $postMsgUtil.trigger(iframe, enKeys + url, {
            data: {
              message: "exitFullscreen success",
            },
          });
          break;
        case "iframeMiddleware":
          // iframe 中间件, iframe 与 iframe 之间的数据传递
          iframeOperations($postMsgUtil, params, iframe, enKeys, url, _vue);
          break;
        default:
          requestUtils($postMsgUtil, url, params, headers, method, responseType, enKeys, iframe);
          break;
      }
    },
    iframe
  );

  // 监听父页面的发送事件
  $postMsgUtil.listen(
    "redirectTo",
    ({ url, route, params, isOpener = false }) => {
      handleRedirectTo(url, route, params, _vue, isOpener)
    },
    iframe
  );
  // 监听父页面的发送事件
  $postMsgUtil.listen(
    "redirectToT",
    ({ path, params, query }) => {
      _vue.$router.push({
        path,
        params,
        query,
      });
    },
    iframe
  );

  // 监听返回
  $postMsgUtil.listen(
    "backToOrigin",
    ({ data, isClose = false }) => {
      handleBackToOrigin(data, isClose, _vue);
    },
    iframe
  );

  // 注册消息推送事件监听
  $postMsgUtil.listen(
    "registerNoticePush",
    (data) => {
      // 把消息推送来源
      data.originIframeId = iframe.getAttribute("id");
      _vue.$store.dispatch("app/addNoticePushQueues", {
        data,
      });
    },
    iframe
  );

  // 取消消息推送事件监听
  $postMsgUtil.listen(
    "unRegisterNoticePush",
    (data) => {
      _vue.$store.dispatch("app/removeNoticePushQueues", {
        data,
      });
    },
    iframe
  );

  // 注册通用带参数消息推送事件监听 Mark.Yuan 2023.05.16
  $postMsgUtil.listen(
    "registerCommonNoticePush",
    (data) => {
      // 把消息推送来源
      data.originIframeId = iframe.getAttribute("id");
      _vue.$store.dispatch("app/addCommonNoticePushQueues", {
        data,
      });
    },
    iframe
  );

  // 取消通用带参数消息推送事件监听 Mark.Yuan 2023.05.16
  $postMsgUtil.listen(
    "unRegisterCommonNoticePush",
    (data) => {
      _vue.$store.dispatch("app/removeCommonNoticePushQueues", {
        data,
      });
    },
    iframe
  );

  // 消息跳转至指定的大屏页面
  $postMsgUtil.listen(
    "noticeRedirectTo",
    function (data) {
      _vue.$store.dispatch("app/noticeRedirectQueues", data);
    },
    iframe
  );

  //接收redirectToLookHerelisten传递过来的数据
  $postMsgUtil.listen(
    "lookHerelisten",
    function (data) {
      _vue.$store.dispatch("lookHere/lookHereData", data);
    },
    iframe
  );

  //接收多视频传递来的消息
  $postMsgUtil.listen(
    "linkVideoDialogListen",
    function (data) {
      _vue.$store.dispatch("linkVideo/linkVideoData", data);
    },
    iframe
  );

  //接收视图联动关闭消息
  $postMsgUtil.listen(
    "redirectTocloseVideoListen",
    function (data) {
      _vue.$store.dispatch("lookHere/isCloseVideoListen", data);
    },
    iframe
  );
  // 大屏之间互相跳转
  $postMsgUtil.listen('redirectToOtherPage', ({ url, params = {}, isOpener = false }) => {
    redirectToOtherPage({ url, params, isOpener });
  }, iframe)

  // 监听地图2.0操作
  $postMsgUtil.listen(
    "mapOLMiddleWare",
    function (data) {
      handleMapOLMiddleWare(data,$postMsgUtil, iframe, _vue);
    },
    iframe
  );

  // 数字人打开大屏操作
  $postMsgUtil.listen(
    "intelligentMiddleCmdOpen",
    (data) => {
      console.log("数字人打开大屏操作->:intelligentMiddleCmdOpen", data);
      EventBus.$emit("intelligentMiddleCmdOpen", data);
    },
    iframe
  );


  // 林业AR消息
  $postMsgUtil.listen(
    "listenLyMessage",
    (data) => {
      console.log("listenLyMessage", data);
      EventBus.$emit("openArBanner", data);
    },
    iframe
  );

  // 飞行大屏
  $postMsgUtil.listen(
    "listenUavToFlyMessage",
    (data) => {
      console.log("listenUavToFlyMessage", data);
      EventBus.$emit("openUavToFlyBanner", data);
    },
    iframe
  );
  // 飞行管理切换Src 消息
  $postMsgUtil.listen(
    "listenChangeMenuSrc",
    (data) => {
      handleListenChangeMenuSrc(data, _vue);
    },
    iframe
  );
  //监听跳转应急管理大屏消息
  $postMsgUtil.listen(
    "jumpToEmergencyManage",
    (data) => {
      console.log("jumpToEmergencyManage", data);
      EventBus.$emit("openEmergencyManage", data);
    },
    iframe
  );
  //监听跳转应急指挥大屏消息
  $postMsgUtil.listen(
    "jumpToEmergencyCommand",
    (data) => {
      console.log("jumpToEmergencyCommand", data);
      EventBus.$emit("openEmergencyCommand", data);
    },
    iframe
  );
};

export function actionLister(iframe, options) {
  const $postMsgUtil =
    iframe.getAttribute("data-mode") === "full"
      ? Vue.prototype.postMsgUtil
      : postMsgUtil;
  $postMsgUtil.trigger(iframe, "mapDomEventMiddleWare", {
    data: {
      ...options,
    },
  });
}
